{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Ordinal Regression"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import scipy.stats as stats\n",
    "\n",
    "from statsmodels.miscmodels.ordinal_model import OrderedModel"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Loading a stata data file from the UCLA website.This notebook is inspired by https://stats.idre.ucla.edu/r/dae/ordinal-logistic-regression/ which is a R notebook from UCLA."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "url = \"https://stats.idre.ucla.edu/stat/data/ologit.dta\"\n",
    "data_student = pd.read_stata(url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_student.head(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_student.dtypes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_student['apply'].dtype"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This dataset is about the probability for undergraduate students to apply to graduate school given three exogenous variables:\n",
    "- their grade point average(`gpa`), a float between 0 and 4.\n",
    "- `pared`, a binary that indicates if at least one parent went to graduate school.\n",
    "- and `public`, a binary that indicates if the current undergraduate institution of the student is public or private.\n",
    "\n",
    "`apply`, the target variable is categorical with ordered categories: `unlikely` < `somewhat likely` < `very likely`. It is a `pd.Serie` of categorical type, this is preferred over NumPy arrays."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The model is based on a numerical latent variable $y_{latent}$ that we cannot observe but that we can compute thanks to exogenous variables.\n",
    "Moreover we can use this $y_{latent}$ to define $y$ that we can observe.\n",
    "\n",
    "For more details see the the Documentation of OrderedModel,  [the UCLA webpage](https://stats.idre.ucla.edu/r/dae/ordinal-logistic-regression/) or this [book](https://onlinelibrary.wiley.com/doi/book/10.1002/9780470594001).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Probit ordinal regression:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mod_prob = OrderedModel(data_student['apply'],\n",
    "                        data_student[['pared', 'public', 'gpa']],\n",
    "                        distr='probit')\n",
    "\n",
    "res_prob = mod_prob.fit(method='bfgs')\n",
    "res_prob.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In our model, we have 3 exogenous variables(the $\\beta$s if we keep the documentation's notations) so we have 3 coefficients that need to be estimated.\n",
    "\n",
    "Those 3 estimations and their standard errors can be retrieved in the summary table.\n",
    "\n",
    "Since there are 3 categories in the target variable(`unlikely`, `somewhat likely`, `very likely`), we have two thresholds to estimate. \n",
    "As explained in the doc of the method `OrderedModel.transform_threshold_params`, the first estimated threshold is the actual value and all the other thresholds are in terms of cumulative exponentiated increments. Actual thresholds values can be computed as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_of_thresholds = 2\n",
    "mod_prob.transform_threshold_params(res_prob.params[-num_of_thresholds:])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Logit ordinal regression:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mod_log = OrderedModel(data_student['apply'],\n",
    "                        data_student[['pared', 'public', 'gpa']],\n",
    "                        distr='logit')\n",
    "\n",
    "res_log = mod_log.fit(method='bfgs', disp=False)\n",
    "res_log.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predicted = res_log.model.predict(res_log.params, exog=data_student[['pared', 'public', 'gpa']])\n",
    "predicted"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pred_choice = predicted.argmax(1)\n",
    "print('Fraction of correct choice predictions')\n",
    "print((np.asarray(data_student['apply'].values.codes) == pred_choice).mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Ordinal regression with a custom cumulative cLogLog distribution:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In addition to `logit` and `probit` regression, any continuous distribution from `SciPy.stats` package can be used for the `distr` argument. Alternatively, one can define its own distribution simply creating a subclass from `rv_continuous` and implementing a few methods."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# using a SciPy distribution\n",
    "res_exp = OrderedModel(data_student['apply'],\n",
    "                           data_student[['pared', 'public', 'gpa']],\n",
    "                           distr=stats.expon).fit(method='bfgs', disp=False)\n",
    "res_exp.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# minimal definition of a custom scipy distribution.\n",
    "class CLogLog(stats.rv_continuous):\n",
    "    def _ppf(self, q):\n",
    "        return np.log(-np.log(1 - q))\n",
    "\n",
    "    def _cdf(self, x):\n",
    "        return 1 - np.exp(-np.exp(x))\n",
    "\n",
    "\n",
    "cloglog = CLogLog()\n",
    "\n",
    "# definition of the model and fitting\n",
    "res_cloglog = OrderedModel(data_student['apply'],\n",
    "                           data_student[['pared', 'public', 'gpa']],\n",
    "                           distr=cloglog).fit(method='bfgs', disp=False)\n",
    "res_cloglog.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Using formulas - treatment of endog\n",
    "\n",
    "Pandas' ordered categorical and numeric values are supported as dependent variable in formulas. Other types will raise a ValueError."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "modf_logit = OrderedModel.from_formula(\"apply ~ 0 + pared + public + gpa\", data_student,\n",
    "                                      distr='logit')\n",
    "resf_logit = modf_logit.fit(method='bfgs')\n",
    "resf_logit.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using numerical codes for the dependent variable is supported but loses the names of the category levels. The levels and names correspond to the unique values of the dependent variable sorted in alphanumeric order as in the case without using formulas."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_student[\"apply_codes\"] = data_student['apply'].cat.codes * 2 + 5\n",
    "data_student[\"apply_codes\"].head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "OrderedModel.from_formula(\"apply_codes ~ 0 + pared + public + gpa\", data_student,\n",
    "                          distr='logit').fit().summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "resf_logit.predict(data_student.iloc[:5])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using string values directly as dependent variable raises a ValueError."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_student[\"apply_str\"] = np.asarray(data_student[\"apply\"])\n",
    "data_student[\"apply_str\"].head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_student.apply_str = pd.Categorical(data_student.apply_str, ordered=True)\n",
    "data_student.public = data_student.public.astype(float)\n",
    "data_student.pared = data_student.pared.astype(float)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "raises-exception"
    ]
   },
   "outputs": [],
   "source": [
    "OrderedModel.from_formula(\"apply_str ~ 0 + pared + public + gpa\", data_student,\n",
    "                          distr='logit')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Using formulas - no constant in model\n",
    "\n",
    "The parameterization of OrderedModel requires that there is **no** constant in the model, neither explicit nor implicit. The constant is equivalent to shifting all thresholds and is therefore not separately identified.\n",
    "\n",
    "Patsy's formula specification does not allow a design matrix without explicit or implicit constant if there are categorical variables (or maybe splines) among explanatory variables. As workaround, statsmodels removes an explicit intercept. \n",
    "\n",
    "Consequently, there are two valid cases to get a design matrix without intercept.\n",
    "\n",
    "- specify a model without explicit and implicit intercept which is possible if there are only numerical variables in the model.\n",
    "- specify a model with an explicit intercept which statsmodels will remove.\n",
    "\n",
    "Models with an implicit intercept will be overparameterized, the parameter estimates will not be fully identified, `cov_params` will not be invertible and standard errors might contain nans.\n",
    "\n",
    "In the following we look at an example with an additional categorical variable.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nobs = len(data_student)\n",
    "data_student[\"dummy\"] = (np.arange(nobs) < (nobs / 2)).astype(float)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**explicit intercept**, that will be removed:\n",
    "\n",
    "Note \"1 +\" is here redundant because it is patsy's default."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "modfd_logit = OrderedModel.from_formula(\"apply ~ 1 + pared + public + gpa + C(dummy)\", data_student,\n",
    "                                      distr='logit')\n",
    "resfd_logit = modfd_logit.fit(method='bfgs')\n",
    "print(resfd_logit.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "modfd_logit.k_vars"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "modfd_logit.k_constant"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**implicit intercept** creates overparameterized model\n",
    "\n",
    "Specifying \"0 +\" in the formula drops the explicit intercept. However, the categorical encoding is now changed to include an implicit intercept. In this example, the created dummy variables `C(dummy)[0.0]` and `C(dummy)[1.0]` sum to one."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": [
     "raises-exception"
    ]
   },
   "source": [
    "```python\n",
    "OrderedModel.from_formula(\"apply ~ 0 + pared + public + gpa + C(dummy)\", data_student, distr='logit')\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "To see what would happen in the overparameterized case, we can avoid the constant check in the model by explicitly specifying whether a constant is present or not. We use hasconst=False, even though the model has an implicit constant.\n",
    "\n",
    "The parameters of the two dummy variable columns and the first threshold are not separately identified. Estimates for those parameters and availability of standard errors are arbitrary and depends on numerical details that differ across environments.\n",
    "\n",
    "Some summary measures like log-likelihood value are not affected by this, within convergence tolerance and numerical precision. Prediction should also be possible. However, inference is not available, or is not valid."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "modfd2_logit = OrderedModel.from_formula(\"apply ~ 0 + pared + public + gpa + C(dummy)\", data_student,\n",
    "                                         distr='logit', hasconst=False)\n",
    "resfd2_logit = modfd2_logit.fit(method='bfgs')\n",
    "print(resfd2_logit.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "resfd2_logit.predict(data_student.iloc[:5])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "resf_logit.predict()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Binary Model compared to Logit\n",
    "\n",
    "If there are only two levels of the dependent ordered categorical variable, then the model can also be estimated by a Logit model.\n",
    "\n",
    "The models are (theoretically) identical in this case except for the parameterization of the constant. Logit as most other models requires in general an intercept. This corresponds to the threshold parameter in the OrderedModel, however, with opposite sign.\n",
    "\n",
    "The implementation differs and not all of the same results statistic and post-estimation features are available. Estimated parameters and other results statistic differ mainly based on convergence tolerance of the optimization.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from statsmodels.discrete.discrete_model import Logit\n",
    "from statsmodels.tools.tools import add_constant"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We drop the middle category from the data and keep the two extreme categories."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mask_drop = data_student['apply'] == \"somewhat likely\"\n",
    "data2 = data_student.loc[~mask_drop, :]\n",
    "# we need to remove the category also from the Categorical Index\n",
    "data2['apply'].cat.remove_categories(\"somewhat likely\", inplace=True)\n",
    "data2.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mod_log = OrderedModel(data2['apply'],\n",
    "                        data2[['pared', 'public', 'gpa']],\n",
    "                        distr='logit')\n",
    "\n",
    "res_log = mod_log.fit(method='bfgs', disp=False)\n",
    "res_log.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Logit model does not have a constant by default, we have to add it to our explanatory variables.\n",
    "\n",
    "The results are essentially identical between Logit and ordered model up to numerical precision mainly resulting from convergence tolerance in the estimation.\n",
    "\n",
    "The only difference is in the sign of the constant, Logit and OrdereModel have opposite signs of he constant. This is a consequence of the parameterization in terms of cut points in OrderedModel instead of including and constant column in the design matrix."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ex = add_constant(data2[['pared', 'public', 'gpa']], prepend=False)\n",
    "mod_logit = Logit(data2['apply'].cat.codes, ex)\n",
    "\n",
    "res_logit = mod_logit.fit(method='bfgs', disp=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res_logit.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Robust standard errors are also available in OrderedModel in the same way as in discrete.Logit.\n",
    "As example we specify HAC covariance type even though we have cross-sectional data and autocorrelation is not appropriate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res_logit_hac = mod_logit.fit(method='bfgs', disp=False, cov_type=\"hac\", cov_kwds={\"maxlags\": 2})\n",
    "res_log_hac = mod_log.fit(method='bfgs', disp=False, cov_type=\"hac\", cov_kwds={\"maxlags\": 2})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res_logit_hac.bse.values - res_log_hac.bse"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
